package com.device_manager.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import com.device_manager.service.OssService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Slf4j
@Data
@AllArgsConstructor
@NoArgsConstructor
public class OssServiceImpl implements OssService {
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;
    @Value("${aliyun.oss.access-key-id}")
    private String accessKeyId;
    @Value("${aliyun.oss.access-key-secret}")
    private String accessKeySecret;

    @Override
    public String uploadFile(MultipartFile file, String folder) {
        if (file == null || file.isEmpty()) return null;

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            String fileName = generateFileName(folder, file.getOriginalFilename());
            ossClient.putObject(bucketName, fileName, file.getInputStream());
            return generateAccessUrl(fileName);
        } catch (IOException e) {
            log.error("文件上传失败: {}", e.getMessage());
            throw new RuntimeException("文件上传失败", e);
        } finally {
            ossClient.shutdown();
        }
    }

    @Override
    public List<String> uploadFiles(List<MultipartFile> files, String folder) {
        return files.stream()
                .filter(file -> !file.isEmpty())
                .map(file -> uploadFile(file, folder))
                .collect(Collectors.toList());
    }

    @Override
    public String uploadVideo(MultipartFile videoFile) {
        // 视频上传单独处理（可添加视频格式验证）
        if (videoFile == null || videoFile.isEmpty()) return null;

        String originalFilename = videoFile.getOriginalFilename();
        if (!originalFilename.matches(".*\\.(mp4|mov|avi)$")) {
            throw new IllegalArgumentException("仅支持mp4/mov/avi格式视频");
        }

        return uploadFile(videoFile, "videos/");
    }

    private String generateFileName(String folder, String originalName) {
        return folder + UUID.randomUUID() + "_" + originalName;
    }

    private String generateAccessUrl(String fileName) {
        return "https://" + bucketName + "." + endpoint + "/" + fileName;
    }
}
